package com.xywy.bloodandroid.act;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.xywy.bloodandroid.R;
import com.xywy.bloodandroid.base.BaseActivity;
import com.xywy.bloodandroid.bean.User;
import com.xywy.bloodandroid.util.Constants;
import com.xywy.bloodandroid.util.HttpUtil;
import com.xywy.bloodandroid.util.UIUtil;
import com.xywy.bloodandroid.util.HttpUtil.ResponseCallBack;
import com.xywy.bloodandroid.util.MD5;
import com.xywy.bloodandroid.vollery.OnVolleyResponseListener;
import com.xywy.bloodandroid.vollery.PostRequest;

/**
 * 验证码确认绑定新手机号
 */
public class ComfirmChangePhoneNumberActivity extends BaseActivity {
	String phone_num;

	private TextView middle_title;
	private RelativeLayout left_img;
	private TextView tv_tip;
	private EditText ed_input_signCode;
	private Button btn_bind;

	private String id;

	private Object signs;

	@Override
	protected void initView(Bundle savedInstanceState) {
		setContentView(R.layout.activity_comfirm_change_phone_number);
		dataFromPreAct();
		middle_title = (TextView) findViewById(R.id.middle_title);
		middle_title.setText("验证码确认");
		left_img = (RelativeLayout) findViewById(R.id.left_img);
		tv_tip = (TextView) findViewById(R.id.tv_tip);
		ed_input_signCode = (EditText) findViewById(R.id.ed_input_signCode);
		btn_bind = (Button) findViewById(R.id.btn_bind);
		btn_bind.setBackgroundResource(R.drawable.login_button_press);
		btn_bind.setClickable(false);
	}

	private void dataFromPreAct() {
		Intent intent = getIntent();
		phone_num = intent.getStringExtra("new_phone_num");
	}

	@Override
	protected void initListener() {
		left_img.setOnClickListener(this);
		btn_bind.setOnClickListener(this);
		ed_input_signCode.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				if (ed_input_signCode.getText().toString().length() == 6) {
					btn_bind.setBackgroundResource(R.drawable.login_button_selector);
					btn_bind.setClickable(true);
				} else {
					btn_bind.setBackgroundResource(R.drawable.login_button_press);
					btn_bind.setClickable(false);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {

			}

			@Override
			public void afterTextChanged(Editable arg0) {

			}
		});
	}

	@Override
	protected void initData() {

		id = getIntent().getStringExtra("id");
		String phone_num_1 = phone_num.substring(0, 3);
		String phone_num_2 = phone_num.substring(3, 7);
		String phone_num_3 = phone_num.substring(7, 11);
		tv_tip.setText("我们已经下发 验证码 到这个手机号:\n" + phone_num_1 + " " + phone_num_2
				+ " " + phone_num_3);
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.left_img:
			ComfirmChangePhoneNumberActivity.this.finish();
			break;

		case R.id.btn_bind:
			String sign = ed_input_signCode.getText().toString().trim();
			if (sign.length() == 6) {
				submit();
				// showToast("没有写接口");
			} else {
				showToast("请检查您的验证码");
			}
			break;
		}
	}

	/**
	 * 提交验证码
	 */
	void submit() {
		 signs = null;
		try {
			signs = MD5.md5s(Constants.Sign + Constants.tag);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String url = "http://api.wws.xywy.com/index.php?act=sms&fun=verifyCode&target="
				+ phone_num
				+ "&tag="
				+ Constants.tag
				+ "&code="
				+ ed_input_signCode.getText().toString().trim()
				+ "&yz=1"
				+ "&sign=" + signs + "&type=3";
//				+"&PHPSESSID="+id;
		System.out.println("------------"+url);
		HttpUtil.httpclientDoGet(url, new ResponseCallBack() {
			
			@Override
			public void success(String result) {
				// TODO Auto-generated method stu
				try {
					JSONObject jsonObject = new JSONObject(result);
					int code = jsonObject.getInt("code");
					if (code == 10000) {
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								// TODO Auto-generated method stub
								User.getInstance(context).setPhonenum(phone_num);
								bindNewNumber();
								showToast("验证成功");
							}

							private void bindNewNumber() {
								// TODO Auto-generated method stub
								String url = "http://api.wws.xywy.com/index.php?act=kbb&fun=resetProperty&userid="
										+ User.getInstance(context).getUserid()
										+ "&tag="
										+ Constants.tag
										+ "&sign=" + signs;
								PostRequest<String> postRequest = new PostRequest<String>(url,
										String.class, new OnVolleyResponseListener<String>() {

											@Override
											public void onError(VolleyError volleyError) {
												UIUtil.DissDialog(context, waittingDialog);
												Toast.makeText(context, "提交失败！", Toast.LENGTH_SHORT)
														.show();

											}

											@Override
											public void onSuccess(String response) {
												UIUtil.DissDialog(context, waittingDialog);
												if (response != null) {
													JSONObject jsonObject;
													try {
														jsonObject = new JSONObject(response);
														String state = jsonObject.getString("state");
														if (state.equals("200")) {
															Toast.makeText(context, "提交成功！",
																	Toast.LENGTH_SHORT).show();
															finish();
														}
													} catch (JSONException e) {
														e.printStackTrace();
													}

												}
											}
										});
								HashMap<String, String> params = new HashMap<String, String>();
								params.put("userid", User.getInstance(context).getUserid());// userid
								params.put("keyword", "phonenum");
								params.put("value", phone_num);
								postRequest.setIsParseJson(false);
								postRequest.setParams(params);
								executeRequest(postRequest);
							}
						});
					} else {
						showToast(jsonObject.getString("error"));
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void error(Exception e) {
				// TODO Auto-generated method stub
			}
		});

//		GetRequest<String> getRequest = new GetRequest<String>(url,
//				String.class, new OnVolleyResponseListener<String>() {
//
//					@Override
//					public void onError(VolleyError volleyError) {
//						showToast("提交失败");
//					}
//
//					@Override
//					public void onSuccess(String response) {
//						try {
//							JSONObject jsonObject = new JSONObject(response);
//							int code = jsonObject.getInt("code");
//							if (code == 10000) {
//								showToast("提交成功");
//								finish();
//							} else {
//								showToast(jsonObject.getString("error"));
//							}
//
//						} catch (JSONException e) {
//							e.printStackTrace();
//						}
//
//					}
//
//				});
//
//		getRequest.setIsParseJson(false);
//		VolleyManager.addRequest(getRequest, "");

	}

}
